package estore.service;

import estore.model.User;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务类
 */
public class UserService {
    private final Map<String, User> userData = new HashMap<>();
    private final String dataFilePath = "users.dat";

    public UserService() {
        loadData();
        initDefaultUsers();
    }

    private void initDefaultUsers() {
        if (userData.isEmpty()) {
            // 添加默认管理员用户
            userData.put("admin", new User("admin", "admin123", "admin@estore.com", "admin"));
            // 添加默认普通用户
            userData.put("user", new User("user", "user123", "user@estore.com", "user"));
            saveData();
        }
    }

    public User authenticateUser(String username, String password) {
        User user = userData.get(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    public User getUserByUsername(String username) {
        return userData.get(username);
    }

    public boolean addUser(User user) {
        if (userData.containsKey(user.getUsername())) {
            return false;
        }
        userData.put(user.getUsername(), user);
        saveData();
        return true;
    }

    public boolean updateUser(User user) {
        if (!userData.containsKey(user.getUsername())) {
            return false;
        }
        userData.put(user.getUsername(), user);
        saveData();
        return true;
    }

    public List<User> getAllUsers() {
        return new ArrayList<>(userData.values());
    }

    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(userData);
        } catch (IOException e) {
            System.err.println("保存用户数据失败: " + e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    private void loadData() {
        File file = new File(dataFilePath);
        if (!file.exists()) return;

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFilePath))) {
            Map<String, User> loadedData = (Map<String, User>) ois.readObject();
            userData.putAll(loadedData);
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("加载用户数据失败: " + e.getMessage());
        }
    }

    public void backupData() {
        String backupFilePath = dataFilePath + ".bak";
        try (FileInputStream fis = new FileInputStream(dataFilePath);
             FileOutputStream fos = new FileOutputStream(backupFilePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            System.err.println("备份用户数据失败: " + e.getMessage());
        }
    }
}
